package com.google.jacli.compiler;

import java.lang.reflect.Field;
import java.util.List;
import com.google.jacli.Argument;

public class OptionCompiler extends AbstractCompiler {

    public void compile(final List<Field> fieldList, final Object target, final String[] args) {
        boolean done = false;
        for (Field field : fieldList) {
            if (done) {
                return;
            }
            Argument argument = getArgument(field);
            if (field.getType() == Boolean.class || field.getType() == boolean.class) {
                if (hasOption(argument, args)) {
                    setValue(field, target, "true");                    
                } else {
                    setValue(field, target, "false");
                }
            } else if (argument.option().length() > 0) {
                List<String> optionValues = getOptionValue(argument, args);
                
                if (optionValues.isEmpty()) {
                    if (!argument.required()) {
                        continue;
                    }
                    if (argument.defaultValue().length() != 0) {
                        optionValues.add(argument.defaultValue());
                    } else {
                        this.command.getExceptions().add(new IllegalArgumentException("Required option ["
                                                                                      + argument.option()
                                                                                      + "] is missing or it contains no value"));
                    }
                }

                for (String optionValue : optionValues) {
                    setValue(field, target, optionValue);
                }
            } else {
                setValue(field, target, args[args.length - 1]);
                // this should be the last option in case of optionBased parse
                done = true;
            }
        }
    }
}
